package com.estrend.redbird.ui.start

import android.app.Application
import androidx.lifecycle.viewModelScope
import com.estrend.redbird.RedBirdApplication
import com.estrend.redbird.base.BaseRedBirdViewModel
import com.estrend.redbird.bean.ResponseStartData
import com.estrend.redbird.net.ApiService
import com.estrend.redbird.net.SessionIdManager
import com.estrend.redbird.utils.DeviceUtils
import com.estrend.redbird.utils.RequestBuilder
import com.king.frame.mvvmframe.base.BaseViewModel
import com.king.frame.mvvmframe.data.DataRepository
import com.king.frame.mvvmframe.data.Repository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.catch

import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class StartViewModel @Inject constructor(private val repository: Repository,
                                         application: Application): BaseRedBirdViewModel(application) {

    private val apiService by lazy {
        repository.getRetrofitService(ApiService::class.java)
    }
    private var response = MutableStateFlow<ResponseStartData?>(null)
    fun getData(){
        viewModelScope.launch(Dispatchers.IO) {
            val token = RequestBuilder()
                .addParam(SessionIdManager.getServiceConstant())
                .addParam("")
                .addParam(DeviceUtils.getDeviceUniqueId(RedBirdApplication.mContext))
                .addParam("")
                .addParam(DeviceUtils.getDeviceModel())
                .addParam(DeviceUtils.getDeviceName())
                .addParam(DeviceUtils.getSDKVersion())
                .addParam(DeviceUtils.getAndroidVersion())
                .addParam(DeviceUtils.getManufacturer())
                .addParam(DeviceUtils.getScreenSizeInInches(RedBirdApplication.mContext).toString())
                .addParam(DeviceUtils.getHiegtWidth(RedBirdApplication.mContext))
                .build()
            apiService.startPage(token).onStart {
               showLoading()
            }
                .catch {
                hideLoading()
            }.collect{
                SessionIdManager.setSessionId(it.unhappiness)
                hideLoading()
            }
        }

    }
}